/**
 * ElasticsearchConnection.java
 *
 * @author: ZhuJiahui
 * @date: 2018/12/9 15:36
 */
package com.zhujiahui.elasticsearch.connection;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: ZhuJiahui
 * @version: 1.0
 */
public class ElasticsearchConnection {

    public final static String HOST = "127.0.0.1";
    // http请求的端口是9200，客户端是9300
    public final static int PORT = 9300;

    // 创建client
    private static TransportClient transportClient = null;

    public ElasticsearchConnection() {

    }

    public static TransportClient getConnection() {
        //
        //Settings settings = Settings.builder().put("cluster.name", "nmtx-cluster").build();

        try {
            transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddresses(
                            new TransportAddress(InetAddress.getByName(HOST),
                                    PORT));

        } catch (UnknownHostException e) {
            e.printStackTrace();
            transportClient.close();
        }
        return transportClient;
    }

    public void closeConnection() {
        if (transportClient != null) {
            transportClient.close();
        }
    }

    public static void main(String[] args) {
        TransportClient transportClient =
                ElasticsearchConnection.getConnection();
        System.out.println(transportClient.toString());
    }
}
